<template>
  <view style="display: flex;flex-direction: column;align-items: center;">
    <view style="background-color: white; width: 100%;height: 60rpx">
      <!-- 这里是状态栏 -->
    </view>
    <!-- 这里是状态栏右侧的list按钮 -->
    <uni-nav-bar style=" width: 100%;" color="#000" left-icon="left" @clickLeft="navBack()" right-icon="list"
                 @clickRight="clickexpert___()" :title="title"/>

    <view class="group_2">
      <view class="equip_name_box">
        {{ experName || '暂未选择实验' }}
        <image class="al-assistant" src="../../static/images/al-assistant.png" @click="openAssistant"></image>
      </view>
      <image class="image_7 pos_4" src="../../static/images/a512c5fcd446c7a2d166e1f937a348b1.png"/>
      <text class="font_2 text_5 pos_6">{{ status }}</text>
    </view>
    <view class="group_3">
      <image class="image_8" src="../../static/images/finally.png"/>
      <view class="status_container">
        <text class="status_1" :style="{ color: getStatusColor(status) }">{{ getStatusText(status) }}</text>
      </view>
    </view>

    <view class="title_box">
      <view class="progress_circle">
        <view class="progress_block">
          <view class="name">实验时间</view>
          <view class="value">{{ envir.time }}分钟</view>
        </view>
        <view class="progress_block">
          <view class="name">炉内温度</view>
          <view class="value">{{ envir.temp_now }}℃</view>
        </view>
      </view>
    </view>
    <view class="charts-box">
      <qiun-data-charts type="area" :eopts="opts3" :chartData="chartData2" :animation="false" :ontouch="true"
                        :onzoom="true" :disableScroll="true" :echartsH5="true" :echartsApp="true"></qiun-data-charts>
    </view>

    <view class="button_box_1">
      <view class="button-container">
        <view class="button" @click="turnOn()" :style="{'background-color': buttonColor}">{{ button_on_off }}
        </view>
        <view class="button" @click="clickSetExperButton()">设置实验</view>
        <view class="button" @click="startExper()" :style="{'background-color': buttonColor1}">
          {{ expertStatus }}
        </view>
      </view>
    </view>
    <!--弹出泡-->
    <chunLei-popups v-model="showPopups" maskBg="rgba(0,0,0,0.5)" :popData="laboratoryList" @tapPopup="tapPopup"
                    :x="x" :y="y" :triangle="false" style="font-size: 40rpx" dynamic>
    </chunLei-popups>
    <view v-if="equipcontroller_zzc">
      <view class="flex-col justify-start items-end expert1 pos1">
        <equipcontroller_zzc></equipcontroller_zzc>
      </view>

      <view class="zzc"></view>
    </view>
    <button v-if="equipcontroller_zzc" @click.stop="zzc1()" class="cancel"
            style="margin: 0 ;text-align: center; background-color: #b3b3b3;">
      <view style="font-size:31.5rpx ; color: white; ">取消</view>
    </button>
    <next-modal
        @confirm="toStartExper"
        :show="modalCustomShow"
        :title="`注意`"
        confirmColor="#000"
        :showCancel="false"
        :autoClose="false"
    >
      <!--注意插槽的使用的优先级大于next-modal组件的props的值-->
      <!--自定义content内容-->
      <view slot="content">
        <view class="modal-content">
          <text class="content">实验即将开始,请创建六位控制码。尽量不要退出此页面。</text>
          <input class="input" v-model="controlCode" maxlength="6"
                 placeholder="控制码"/>
        </view>
      </view>
      <!--自定义footer内容-->
    </next-modal>
    <next-modal
        @confirm="getPermissionWrapper"
        @cancel="navBack"
        :show="getPermissionShow"
        :title="`注意`"
        confirmColor="#000"
        :showCancel="true"
        :autoClose="false"
    >
      <!--注意插槽的使用的优先级大于next-modal组件的props的值-->
      <!--自定义content内容-->
      <view slot="content">
        <view class="modal-content">
          <text class="content">请输入六位控制码，以获取实验权限。</text>
          <input class="input" v-model="controlCode" maxlength="6"
                 placeholder="控制码"/>
        </view>
      </view>
      <!--自定义footer内容-->
    </next-modal>
    
    <!-- AL助手弹窗 -->
    <al-assistant-popup ref="assistantPopup" @popup-visible-change="onPopupVisibleChange"></al-assistant-popup>
  </view>

</template>

<script>
import {
  mapState,
  mapMutations
} from 'vuex';
//保存实验历史数据
import {
  _saveHistory
} from '@/service/history.js'

//进度条
import cmdCircle from "@/components/cmd-circle/cmd-circle.vue"

import expert___ from '@/components/expert___/expert___.vue';
import onheating_c from '@/components/onheating_c/onheating_c.vue';
import equipcontroller_zzc from '@/components/equipcontroller_zzc.vue';
import AlAssistantPopup from '@/components/al-assistant-popup.vue';

import cmdProgress from "@/components/cmd-progress/cmd-progress.vue"
//根据设备序列号查询设备信息
import {
  _changename,
  _getequipsinfo
} from '@/service/equip.js'
//上传数据
import {
  _checkTime, _getPermission,
  _getSomeData, _initExperData, _isController,
  _pauseRecordTime,
  _resumeRecordTime,
  _sendcontroldata, _setControlCode,
  _startRecordTime
} from '@/service/exper_api.js'


import {
  _saveover
} from '@/service/exper_api.js'

import {
  _changestatus
} from '@/service/equip.js'
import {
  _test
} from '@/service/exper_api.js'
import {
  _searchTemp
} from "@/service/exper_api";
import {
  _removeMessage,
  _postUserInfo,
  _reSetUser
} from "@/service/exper_api.js"
import QiunDataCharts from "../../uni_modules/qiun-data-charts/components/qiun-data-charts/qiun-data-charts.vue";
import ChunLeiPopups from "../../components/chunLei-popups/chunLei-popups.vue";
import {
  _getChartData,
  _sendChartInitData
} from "../../service/exper_api";
import NextModal from "../../uni_modules/next-modal/components/next-modal/next-modal.vue";
import {_getbyid} from '@/service/myexper_api.js';
export default {
  components: {
    NextModal,
    ChunLeiPopups,
    QiunDataCharts,
    cmdProgress,
    cmdCircle,
    onheating_c,
    expert___,
    equipcontroller_zzc,
    AlAssistantPopup
  },
  computed: {
    ...mapState(['hasLogin', 'userInfo', 'accountNum']),
  },

  data() {
    return {
      controlCode: '',
      modalCustomShow: false,
      getPermissionShow: false,
      firstLoad: true,
      equipcontroller_zzc: false,
      hasLoad: false, //验证表格是否正确加载
      buttonColor: '#aaaaaa',
      buttonColor1: '#aaaaaa',
      expertStatus: '', //实验状态
      showPopups: false,
      x: 0,
      y: 0,
      laboratoryList: [{
        title: "设备日志",
        disabled: false,
        // owner_id: this.laboManage[i].owner_id,
        page: "/pages/equipdiary/equipdiary",
        // id: this.laboManage[i].id
      },
        {
          title: "实验记录",
          disabled: false,
          // owner_id: this.laboManage[i].owner_id,
          page: "/pages/experhistory/experhistory",
          // id: this.laboManage[i].id
        },
        {
          title: "添加实验",
          disabled: false,
          // owner_id: this.laboManage[i].owner_id,
          page: "/pages/addmyexper/addmyexper",
          // id: this.laboManage[i].id
        },
        {
          title: "设备信息",
          disabled: false,
          // owner_id: this.lboManage[i].owner_id,
          page: "/pages/device-info/device-info",
          // id: this.laboManage[i].id
        }
      ],
      button_on_off: '',
      socketTask: null,
      // 确保websocket是打开状态
      is_open_socket: false,
      serialnum: '',
      name: '',
      linkinfo: '',
      status: '正在获取中...',
      //原先
      title: '设备连接中...',
      envir: {
        temp: '---',
        temp_now: '---',
        temp_next: '---',
        time: '---'
      },
      totaltime: 0,
      experName: '',
      account_user: '',
      into_exper: '本实验成功完成！',
      last_time: 0,
      chartData1: {
        categories: [],
        series: [{
          name: "预期温度变化折线",
          data: []
        }]
      },
      chartData2: { //貌似图标的显示由此直接控制
        categories: [],
        series: [{
          name: "预期温度",
          label: {
            show: false,
          },
          emphasis: {
            disabled: true,
          },
          data: []
        },
          {
            name: "实际温度",
            label: {
              show: false,
            },
            data: []
          }
        ]
      },
      controlData: [],
      opts3: {
        title: {
          show: true,
          text: '对比温度变化曲线 (℃/S)',
          textStyle: {
            fontSize: 15
          }
        },
        legend: {
          show: true,
          top: "top",
          right: 20,
        },
        xAxis: {
          show: true,
          type: 'category',
          axisTick: {
            show: true,
            alignWithLabel: true //刻度线与标签对齐
          }
        },
        yAxis: {
          show: true,
          // type: 'value',
          splitNumber: 5,
          splitLine: {
            show: false //显示网格线
          },
          axisLine: {
            show: true,
          }
        },
        dataZoom: [{
          type: 'inside',
          preventDefaultMouseMove: true, //解决鼠标移动到图表外导致缩放失效的问题
        }]
      },
      allStatus: {
        "DISCONNECT": {
          text: '设备离线',
          color: '#a6a6a6'
        },
        'CONNECTED': {
          text: '待机',
          color: '#6acdd9'
        },
        'ON': {
          text: '开机',
          color: '#6acdd9'
        },
        'RUN': {
          text: '加热中',
          color: '#6acdd9'
        },
        'OFF': {
          text: '关机',
          color: '#a6a6a6'
        },
        'PULSE': {
          text: '保温中',
          color: '#a6a6a6'
        },
        'STOP': {
          text: '冷却中',
          color: '#a6a6a6'
        }
      },
      // 添加一个标志表示AL助手弹窗是否打开
      isAssistantPopupVisible: false
    }
  },
  onLoad() {
    try {
      const value = uni.getStorageSync('userInfo'); //缓存的用户信息
      if (value != null) {
        this.account_user = value.accountNum; //拿缓存也行，但很怪
      }
    } catch (e) {
      console.error(e);
    }
    uni.getSystemInfo({
      success: (res) => {
        this.opts3.title.textStyle.fontSize = 15 * res.windowWidth / 407;
      }
    });
    try {
      const value = uni.getStorageSync('linkequip');
      //获取缓存中的已连接设备
      if (value != null) {
        this.serialnum = value.serialnum_equip; //设备id
        this.name = value.name_equip;
        console.log(this.serialnum)
      }
    } catch (e) {
      console.error(e);
    }
    this.title = '设备控制';
    this.connectSocketInit(); //第一次加载时只会从这里初始化
    this.refreshExper(); //刷新表格
  },
  onShow() {
    if (this.status == 'DISCONNECT') {
      // this.$api.msg('正在连接设备，请等待...');
      this.equipcontroller_zzc = true;
    }
    this.isController().then(res => {
      if (res === '否') {
        this.getPermissionShow = true;
      }
    });
    if (this.firstLoad == true) {
      this.firstLoad = false;
    } else {
      this.refreshExper(); //刷新表格
      this.connectSocketInit();
    }
  },
  onHide: function () {
    this.hasLoad = false; //卸载表格
    this.closeSocket(); // 在应用关闭时断开WebSocket连接
  },
  beforeDestroy() {
    this.closeSocket(); //页面生命周期结束前，销毁webSocket
  },
  //当页面卸载（包括返回上一个页面、关闭当前页面或切换到其他页面等情况）时执行
  onUnload() {
  },
  onBackPress(e) {
    // 如果AL助手弹窗是打开的，则先关闭弹窗
    if (this.isAssistantPopupVisible) {
      this.$refs.assistantPopup.closePopup();
      this.isAssistantPopupVisible = false;
      return true; // 阻止默认返回行为
    }
    return false; // 使用默认返回行为
  },
  methods: {
    ...mapMutations(['login', 'isSetExper', 'logoutExper']),

    //是否可以控制实验
    async isController() {
      let resultData;
      try {
        resultData = await _isController({
          run_user: this.account_user,
          serialnum_equip: this.serialnum
        });
      } catch (error) {
        throw error; //抛出异常
      }
      if (resultData === undefined || resultData.status !== 200) {
        throw new Error("接口返回异常，位置equipcontroller.vue : isController");
      }
      return resultData.message;
    },
    //获取实验控制权
    async getPermission() {
      let resultData;
      try {
        resultData = await _getPermission({
          run_user: this.account_user,
          controlCode: this.controlCode,
          serialnum_equip: this.serialnum
        });
      } catch (error) {
        throw error; //抛出异常
      }
      if (resultData === undefined || resultData.status !== 200) {
        throw new Error("接口返回异常，位置equipcontroller.vue : getPermission");
      }
      return resultData.message;
    },
    //设置实验控制码
    async setControlCode() {
      let resultData;
      try {
        resultData = await _setControlCode({
          controlCode: this.controlCode,
          serialnum_equip: this.serialnum
        });
        // console.log(resultData)
      } catch (error) {
        throw error; //抛出异常
      }
      if (resultData === undefined || resultData.status !== 200) {
        throw new Error("接口返回异常，位置equipcontroller.vue : setControlCode");
      }
      return resultData.data;
    },
    async getPermissionWrapper() {
      this.getPermission().then(res => {
        if (res === '是') {
          this.getPermissionShow = false;
        } else if (res === '参数错误') {
          this.$api.msg('请输入控制码');
        } else {
          uni.showModal({
            title: '提示',
            content: '请输入正确的控制码',
            showCancel: true,
            cancelText: "返回上一页",
            success: (res) => {
              if (res.confirm) {
                this.controlCode = '';
              } else if (res.cancel) {
                this.navBack();
              }
            }
          });
        }
      })
    },
    //确认开始实验
    async toStartExper(e) {
      if (this.controlCode.length !== 6) {
        this.$api.msg('请正确输入6位控制码');
        return
      }
      this.setControlCode();
      this.initExperData();
      this.hasLoad = true;
      this.modalCustomShow = false
      this.controlCode = '';
    },

    //获取实验中服务器保存的表格对象
    async getChartData() {
      let resultData;
      try {
        resultData = await _getChartData(this.serialnum);
        // console.log(resultData)
      } catch (error) {
        throw error; //抛出异常
      }
      if (resultData === undefined || resultData.status !== 200) {
        throw new Error("接口返回异常，位置equipcontroller.vue : getChartData");
      }
      return resultData.data;
    },
    //开使计时
    async startRecordTime() {
      let resultData;
      try {
        resultData = await _startRecordTime(this.serialnum);
        // console.log(resultData)
      } catch (error) {
        throw error; //抛出异常
      }
      if (resultData === undefined || resultData.status !== 200) {
        throw new Error("接口返回异常，位置equipcontroller.vue : startRecordTime");
      }
      return resultData.data;
    },
    //暂停计时
    async pauseRecordTime() {
      let resultData;
      try {
        resultData = await _pauseRecordTime(this.serialnum);
        // console.log(resultData)
      } catch (error) {
        throw error; //抛出异常
      }
      if (resultData === undefined || resultData.status !== 200) {
        throw new Error("接口返回异常，位置equipcontroller.vue : startRecordTime");
      }
      return resultData.data;
    },
    //恢复计时
    async resumeRecordTime() {
      let resultData;
      try {
        resultData = await _resumeRecordTime(this.serialnum);
        // console.log(resultData)
      } catch (error) {
        throw error; //抛出异常
      }
      if (resultData === undefined || resultData.status !== 200) {
        throw new Error("接口返回异常，位置equipcontroller.vue : startRecordTime");
      }
      return resultData.data;
    },
    async removeMessage() {
      let resultData;
      try {
        resultData = await _removeMessage(this.serialnum);
        console.log(resultData)
      } catch (error) {
        throw error; //抛出异常
      }
      if (resultData == undefined || resultData != undefined && resultData.status != 200) {
        throw new Error("接口返回异常，位置equipcontroller.vue : removeMessage");
      }
      return resultData.data;
    },
    async initExperData(chartStructure) {
      let resultData;
      try {
        resultData = await _initExperData({
          serialnum: this.serialnum,
          temporary: this.controlData,
          experName: this.experName,
          chartStructure: JSON.parse(JSON.stringify(this.chartData2)),
          run_user: this.account_user
        });
        // console.log(resultData)
      } catch (error) {
        throw error; //抛出异常
      }
      if (resultData === undefined || resultData.status !== 200) {
        throw new Error("接口返回异常，位置equipcontroller.vue : initExperData");
      }
      return resultData.data;
    },

    async reSetUser() {
      let data = {
        serialnum_equip: this.serialnum
      }
      console.log(data);
      let result;
      try {
        result = await _reSetUser(data);
      } catch (error) {
        console.log(error + " 接口调用异常");
        throw error; //抛出异常
      }
      return result;
    },
    //遮罩层
    zzc1() {
      this.equipcontroller_zzc = false
    },
    clickexpert___() {
      let dom = uni.createSelectorQuery().in(this);
      // console.log("12333",dom)
      dom.select(".uniui-list").boundingClientRect()
      dom.exec((data) => {
        this.x = (data[0].left + data[0].right) / 2
        this.y = data[0].top + data[0].height
      })
      this.showPopups = !this.showPopups;
    },
    tapPopup(e) {
      if (e.page !== undefined) {
        //最后一个实验室管理功能没有index选项，所以这样判断
        let url = e.page;
        if (e.title === "设备信息") {
          url += '?serialnum_equip=' + encodeURIComponent(this.serialnum);
        }
        uni.navigateTo({
          url: url
        });
      }
    },
    clickequipcontroller_zzc() {
      this.equipcontroller_zzc = !this.equipcontroller_zzc
    },
    turnOn() {
      if (this.button_on_off === '开机') {
        if (this.status === 'DISCONNECT') {
          // this.$api.msg('正在连接设备，请等待...');
          this.clickequipcontroller_zzc()
        } else {
          this.sendRequest('ON')
          this.$api.msg('已发送开机请示！');
          // this.buttonColor = '#68ccd8'
        }
      } else {
        console.log("状态", this.status)
        if (this.status === 'RUN') {
          this.$api.msg('设备正在运行中，无法关闭！请先暂停实验');
          //注意！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！
          //} else if (this.status == 'PULSE'||this.status == 'ON') {
        } else if (this.status === 'PULSE') {
          this.sendRequest('STOP')

          this.$api.msg('正在关机中...');
          // this.buttonColor = '#aaaaaa'
          this.button_on_off = '开机'
        }
      }
    },
    //刷新实验表格
    refreshExper() {
      this.chartData2.categories = [];
      console.log("chartData2", this.chartData2)
      for (let i = 0; i < this.chartData2.series.length; i++) {
        this.chartData2.series[i].data = [];
      }
      try {
        const value = uni.getStorageSync(this.serialnum + 'setexperforequip');
        //获取缓存在本地的实验类型与细节数据
        // console.log("这是什么",value);
        if (value) {
          this.chartData1 = value.chartData; //表格数据，储存“预期温度变化曲线”表格数据
          this.experName = value.expername; //实验名称
          this.envir.temp_next = value.temp_last; //预期最终的加热温度
          this.controlData = value.temporary; //控制参数，对应预设曲线的关键点位。格式如下，为多个js对象
          /*
       {
          "time":0,实验经历时间
          "temp":26,预期温度
          "longtime":10//持续加热时间
       },
         */
          let categories = [];
          let data = [];
          // this.chartData1 = JSON.parse(JSON.stringify({}));
          console.log("chartData1", this.chartData1);
          this.controlData.forEach((temporary, index) => {

            if (index === 0) return;
            const lastDot = this.controlData[index - 1];
            const k = (temporary.temp - lastDot.temp) / ((temporary.time - lastDot.time) * 60);
            console.log(k, temporary.temp, lastDot.temp)
            const startTime = lastDot.time * 60;
            const endTime = temporary.time * 60;
            for (let time = startTime; time <= endTime; ++time) {
              categories.push(time);
              data.push(Number((lastDot.temp + k * (time - startTime)).toFixed(2))); //使用了点斜式
              // data.push(Math.round(lastDot.temp + k * (time - startTime)));//使用了点斜式
            }
          });
          var series = [];
          series.push({
            name: "预期工作温度",
            data
          })
          console.log("chartData1", this.chartData1, categories, series);
          this.totaltime = this.chartData1.categories[this.chartData1.categories.length - 1]; //预期总加热时间
          //concat方法用于多个数组的合并。它将新数组的成员，添加到原数组的尾部，然后返回一个新数组，原数组不变。
          this.chartData2.categories = categories //[].concat(this.chartData1.categories);//将预设实验表格的categories数据导入一个[]并交给最终表格
          this.chartData2.series[0].data = data //[].concat(this.chartData1.series[0].data);//同上
        }
      } catch (e) {
        console.error(e);
      }
    },
    //获取格式化后的日期
    formattedDate(timestamp) {
      const date = new Date(timestamp);
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      const hour = date.getHours().toString().padStart(2, '0');
      const minute = date.getMinutes().toString().padStart(2, '0');
      const second = date.getSeconds().toString().padStart(2, '0');
      const formattedDate = `${year}-${month}-${day} ${hour}:${minute}:${second}`;
      return formattedDate
    },
    startExper() {
      // this.sendRequest('RUN');
      // this.$api.msg('已发送运行命令');
      console.log(this.status)
      console.log(this.experName)
      if (this.expertStatus === '运行') {
        //点击”运行“按钮
        if (this.status === 'DISCONNECT') {
          //离线状态
          this.clickequipcontroller_zzc();
          return;
        }
        if (this.status === 'ON') {
          if (this.experName === '' || this.experName === undefined) {
            uni.showModal({
              content: "请先设置您要进行的实验！",
              showCancel: false,
              success: function (e) {
              }
            });
            return;
          }
          this.modalCustomShow = true;
        } else if (this.status === 'PULSE') {
          this.sendRequest('RUN');
          this.resumeRecordTime();
          this.$api.msg('已发送运行命令');
        }
      } else {
        //点击"暂停按钮"
        this.sendRequest('PULSE');
        this.$api.msg('已发送暂停命令');
        this.pauseRecordTime();
        this.expertStatus = '运行';
      }
    },
    connectSocketInit() {
      // 创建一个this.socketTask对象【发送、接收、关闭socket都由这个对象操作】
      this.socketTask = uni.connectSocket({
        url: 'ws://43.142.102.167:8088/jrl/app/' + this.serialnum + ":" + this.account_user,
        success(data) {
          console.log("websocket连接成功");
        },
      });
      this.socketTask.onOpen((res) => {
        console.log("WebSocket连接正常打开中...！")
        this.is_open_socket = true;
      });
      this.socketTask.onMessage((res) => {
        console.log("收到服务器内容：")
        console.log(res.data)
        this.linkinfo = eval('(' + res.data + ')')
        if (this.linkinfo.response_status === "RESPONSE") {
          this.sendRequest(`RESPONSE:${this.account_user}`);
        }

        if (this.linkinfo?.message) {
          console.log("进入message")
          if (this.linkinfo.message.includes("setExperiment")) {
            const parts = this.linkinfo.message.split("_");
            if (parts.length >= 2) {
              const experId = parts[1];
              this.getExperDataById(experId);
            }
          }else if(this.linkinfo.message=="startExperiment"){
            this.startExper();
          }
          return;
        }
        //设备状态
        this.status = this.linkinfo.equip_status;
        if (this.status == 'DISCONNECT') {
          this.button_on_off = '开机'
          this.expertStatus = '运行'
          this.buttonColor = '#aaaaaa'
          this.buttonColor1 = '#aaaaaa'
        } else if (this.status == 'CONNECTED') {
          this.button_on_off = '开机'
          this.expertStatus = '运行'
          //炉内温度
          this.envir.temp_now = this.linkinfo.current_temperature
          this.buttonColor = '#aaaaaa'
          this.buttonColor1 = '#aaaaaa'
        } else if (this.status == 'ON') {
          this.button_on_off = '关机'
          this.expertStatus = '运行'
          this.buttonColor = '#68ccd8'
          this.buttonColor1 = '#aaaaaa'
        } else if (this.status == 'RUN') {
          this.button_on_off = '关机'
          this.expertStatus = '暂停'
          this.buttonColor = '#68ccd8'
          this.buttonColor1 = '#68ccd8'
        } else if (this.status == 'PULSE') {
          this.button_on_off = '关机'
          this.expertStatus = '运行'
          this.buttonColor = '#68ccd8'
          this.buttonColor1 = '#aaaaaa'
        } else {
          this.button_on_off = '开机'
          this.expertStatus = '运行'
          this.buttonColor = '#aaaaaa'
          this.buttonColor1 = '#aaaaaa'

        }
        try {
          if (this.hasLoad == false) { //没加载完呢，表格数据从服务器拿来重绘
            if ((this.status === 'RUN' || this.status === 'STOP' || this.status === 'PULSE')) {
              //&& this
              //.experName != ""
              this.getChartData().then(res => {
                // console.log("缓存表格", res.series[0]);
                // this.chartData2 = res;
                this.chartData2.categories = res.categories;
                this.chartData2.series[0].data = res.series[0].data
                this.chartData2.series[1].data = res.series[1].data.filter(item => item !== null);

                this.hasLoad = true;
                // this.chartData2 = JSON.parse(JSON.stringify(this.chartData2))
              });
            }
            return;
          }
        } catch (e) {
          console.log(e)
        }

        if (this.hasLoad && this.linkinfo.current_running_time !== null&&this.linkinfo.response_status !== "RESPONSE") {
          this.gettemp1(Math.round(this.linkinfo.current_running_time), this.linkinfo.current_temperature);
        }
      });
      this.socketTask.onClose(() => {
        console.log("已经被关闭了！！！！")
      })
    },
    async getExperDataById(id) {
      console.log(id)
      const res=await this.fetchData(id);
      this.experName = res.name_exper;
      this.details = res.details;
      this.expertotaltime = res.time_exper;
      let categories = [];
      let data = [];
      let series = [];

      this.details.temporary.forEach((temporary, index) => {

        if (index === 0) return;
        const lastDot = this.details.temporary[index - 1];
        const k = (temporary.temp - lastDot.temp) / ((temporary.time - lastDot.time) * 60);
        console.log(k, temporary.temp, lastDot.temp)
        const startTime = lastDot.time * 60;
        const endTime = temporary.time * 60;
        for (let time = startTime; time <= endTime; ++time) {
          categories.push(time);
          data.push(Number((lastDot.temp + k * (time - startTime)).toFixed(2))); //使用了点斜式
          // data.push(Math.round(lastDot.temp + k * (time - startTime)));//使用了点斜式
        }
      });
      series.push({
        name: "预期工作温度",
        label: {
          show: false,
        },
        emphasis: {
          disabled: true,
        },
        data
      })
      let res1 = {
        categories,
        series
      }
      this.chartData1 = JSON.parse(JSON.stringify(res1));


      console.log("chartData1", this.chartData1);
      this.controlData.forEach((temporary, index) => {

        if (index === 0) return;
        const lastDot = this.controlData[index - 1];
        const k = (temporary.temp - lastDot.temp) / ((temporary.time - lastDot.time) * 60);
        console.log(k, temporary.temp, lastDot.temp)
        const startTime = lastDot.time * 60;
        const endTime = temporary.time * 60;
        for (let time = startTime; time <= endTime; ++time) {
          categories.push(time);
          data.push(Number((lastDot.temp + k * (time - startTime)).toFixed(2))); //使用了点斜式
          // data.push(Math.round(lastDot.temp + k * (time - startTime)));//使用了点斜式
        }
      });

      series.push({
        name: "预期工作温度",
        data
      })
      console.log("chartData1", this.chartData1, categories, series);
      this.totaltime = this.chartData1.categories[this.chartData1.categories.length - 1]; //预期总加热时间
      //concat方法用于多个数组的合并。它将新数组的成员，添加到原数组的尾部，然后返回一个新数组，原数组不变。
      this.chartData2.categories =
          categories //[].concat(this.chartData1.categories);//将预设实验表格的categories数据导入一个[]并交给最终表格
      this.chartData2.series[0].data = data //[].concat(this.chartData1.series[0].data);//同上
      // }
    },
    async getexperdata(id) {
      let res;
      try {
        res = await _getbyid(id);
      } catch (error) {
        throw error; //抛出异常
      }
      if (res.flag != true) {
        //console.log(res.data)
        throw new Error("错误")
      }
      return res.data;
    },
    async fetchData(id) {
      const data = await this.getexperdata(id);
      return data;
    },
    gettemp1(time, temp) {
      console.log("实时状态", this.status)
      // try {
      if (time == null || temp == null) {
        if (temp != null) {
          console.log("实时温度", temp)
          this.envir.temp_now = temp; //实时温度一定是要显示的
        }
        console.log("咋停了1")
        return;
      } else if (this.experName == null) {
        console.log("咋停了2")
        return;
      }

      if (this.status == 'CONNECTED' || this.status == 'ON') {
        this.envir.temp_now = temp
      }

      if (this.status != 'ON') {
        // if (this.status == 'RUN') {
        //进度条的百分比肯定是时间百分比，温度百分比不对，如果是有降温的存在，难道百分比还要下降吗？？？？
        this.totaltime = this.chartData2.categories[this.chartData2.categories.length - 1];
        this.envir.temp_now = temp; //实时温度
        // this.envir.time = time; //实验时间化秒为分钟
        this.envir.time = Math.floor(time / 60);

        // console.log("实验时间", this.envir.time)
        let length = this.chartData2.series[1].data.length;
        if (length > 1) {
          this.last_time == 0 ? this.last_time = this.chartData2.categories[length - 1] : null;
          let deltaTime = time - this.last_time;
          let lastTemp = this.chartData2.series[1].data[length - 1];
          let delta = temp - lastTemp;
          let base = deltaTime > 0 ? deltaTime : 10;
          let k = delta / base;
          console.log("基础数据记录",base);
          for (let i = 1; i < base + 1 && this.chartData2.series[1].data.length < this.chartData2.categories
              .length; i++) {
            console.log(delta, k, lastTemp + k * i)
            this.chartData2.series[1].data.push(lastTemp + k * i);
          }
          this.last_time = time;
          // console.log("长度", this.chartData2.series[1].data.length)
        } else {
          this.last_time = time;
          for (let i = 0; i < time; i++) {
            this.chartData2.series[1].data.push(temp);
          }
          console.log("第一次记录",time);
        }
        console.log("实验表格", this.chartData2)
      }
    },
    //销毁webSocket对象
    closeSocket() {
      let self = this;
      this.socketTask.close({
        success(res) {
          self.is_open_socket = false;
          console.log("关闭成功", res);
        },
        fail(err) {
          console.log("关闭失败", err);
        }
      })
    },
    sendRequest(data) {
      if (this.is_open_socket) {
        // websocket的服务器的原理是:发送一次消息,同时返回一组数据【否则服务器会进去死循环崩溃】
        this.socketTask.send({
          data: data,
          async success() {
            // console.log("消息发送成功" + data);
          },
        });
      }
    },
    savedata() {
      //保存数据
      uni.showModal({
        title: '已完成',
        confirmColor: '#000000',
        showCancel: false,
        buttonText: '确定',
        success: async function (res) {
          try {
            if (res.confirm) {
              console.log('用户点击确定');
              await this.reSetUser();
              uni.removeStorageSync(this.serialnum + 'setexperforequip'); //删除预设的实验
              this.chartData2 = { //貌似图标的显示由此直接控制
                categories: [],
                series: [{
                  name: "预期温度",
                  label: {
                    show: false,
                  },
                  emphasis: {
                    disabled: true,
                  },
                  data: []
                },
                  {
                    name: "实际温度",
                    label: {
                      show: false,
                    },
                    data: []
                  }
                ]
              };
            } else {
            }
          } catch (e) {
            console.log(e); // 异常处理
          }
        }.bind(this)
      });

    },
    clickSetExperButton() {
      //点击设置实验的按钮
      // console.log(this.status)
      if (this.status == 'DISCONNECT') { //离线
        this.clickequipcontroller_zzc();
      } else {
        this.navTo('/pages/setExper/setExper?serialnum=' + this.serialnum); //反之跳转设置实验界面
      }
    },
    navTo(url) {
      uni.navigateTo({
        url: url,
        success(res) {
          console.log("成功", res)
        },
        fail(res) {
          console.log("失败", res)
        }
      })
    },
    navBack() {
      uni.switchTab({
        url: '/pages/index1/index1'
      })
    },
    // 打开AL助手弹窗
    openAssistant() {
      this.$refs.assistantPopup.open(this.serialnum);
      this.isAssistantPopupVisible = true;
    },
    
    // 处理弹窗状态变化事件
    onPopupVisibleChange(visible) {
      this.isAssistantPopupVisible = visible;
    },
    
    // 处理物理返回键事件
    onBackPress(e) {
      // 如果AL助手弹窗是打开的，则先关闭弹窗
      if (this.isAssistantPopupVisible) {
        this.$refs.assistantPopup.closePopup();
        this.isAssistantPopupVisible = false;
        return true; // 阻止默认返回行为
      }
      return false; // 使用默认返回行为
    },
    
    getStatusText(status) {
      if (this.allStatus[status]) {
        return this.allStatus[status].text;
      }
      return '未知状态'; //默认状态
    },
    getStatusColor(status) {
      if (this.allStatus[status]) {
        return this.allStatus[status].color;
      }
      return '#a6a6a6'; //默认
    }
  }
}
</script>

<style lang="scss">
.modal-content {
  padding: 32rpx 24rpx;

  .content {
    color: #999;
  }

  .input {
    padding: 5px;
    border-bottom: solid #DADADAFF;
  }
}

.zzc {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 3;
  width: 100%;
  height: 100%;
  opacity: 0.5;
  background-color: #000;
}

.cancel {
  width: 290rpx;
  height: 80rpx;
  border-radius: 50rpx;
  z-index: 9999999;
  position: fixed;
  bottom: 80rpx;
}

page {
  // background: $page-color-base;
  background-image: linear-gradient(0deg, #f2fbfca3 20%, #f2fbfca3 66.8%, #2fb9ca7a 91.4%);
}

.group_2 {
  margin-top: 50rpx;
  margin-right: auto;
  margin-left: 30rpx;
}

.title_box {
  margin-top: 50rpx;
  width: 100%;

}

.text-gray {
  font-size: 28rpx;
  color: #999;
  margin-right: 10rpx;
}

.equip_name_box {
  padding-bottom: 10rpx;
  color: #000000;
  font-size: 37.5rpx;
  font-family: WenQuanYiMicroHeiMono;
  line-height: 34.38rpx;
  display: flex;
  align-items: center;
}
.al-assistant {
  width: 80rpx;
  height: 80rpx;
  position: fixed;
  top: 15%;
  right: 20rpx;
  z-index: 2;
  border-radius: 50%;
  box-shadow: 0 8rpx 30rpx rgba(0, 0, 0, 0.2);
  transition: all 0.3s ease;
  cursor: pointer;
}

.al-assistant:active {
  transform: scale(0.9);
}
.progress_circle {
  margin-top: 20rpx;
  margin-bottom: 20rpx;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
  align-items: center;

  .progress_block {
    width: 45%;
    border-radius: 20rpx;
    position: relative;
    overflow: hidden;
    padding-top: 20upx;
    padding-bottom: 20upx;

    .name {
      color: #000000;
      font-size: 30rpx;
      text-align: center;
    }

    .value {
      color: #000000;
      font-size: 55rpx;
      text-align: center;
    }
  }

  .block_0 {
    //background-color: #ffffff;
  }

  .block_1 {
    //background-color: #ffffff;
  }
}

.charts-box {
  height: 500rpx;
  width: 100%;
  margin-bottom: 100rpx;
}

.button_box_1 {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  position: fixed;
  height: 100rpx;
  bottom: 0;
  background-color: #ddd;

  .button-container {
    display: flex;
    justify-content: space-between;
    width: 100%;

    .button {
      flex: 1;
      display: flex;
      justify-content: center;
      align-items: center;
      margin: 0 10upx;
      background-color: #aaa;
      color: #fff;
      height: 80rpx;
      font-size: 33upx;
      border-radius: 50rpx;


    }

    .button:active {
      background-color: darken(#aaa, 10%);
    }
  }
}

.expert1 {
  z-index: 999;
  //padding: 225rpx 0 725rpx;
  margin: 90rpx 0rpx 0rpx 0rpx;
}

.pos1 {
  position: absolute;
  display: flex;
  align-items: center;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
}

.pos11 {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
}

.image_7 {
  // margin-left: 10rpx;
  margin-right: 10rpx;
  border-radius: 50%;
  width: 29.17rpx;
  height: 29.17rpx;
}

.font_2 {
  font-size: 25rpx;
  font-family: SourceHanSansCN;
  line-height: 28.75rpx;

}

.text_5 {
  color: #959eb0;
  line-height: 29.79rpx;
}


.group_3 {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 180rpx;

  .image_8 {
    opacity: 0.4;
    width: 80vw;
    height: 80vw;
    position: absolute;
  }

  .status_container {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    width: 40vw;
    height: 40vw;
    border-radius: 50%;
    background-image: linear-gradient(0deg, #DEDFE0 20%, #E3E6EC 66.8%, #DEDFE0 91.4%);
    z-index: 1;
  }

  .status_1 {
    font-size: 65rpx;
    color: #959eb0;
    margin-top: 15rpx;
  }
}
</style>